package com.telit.communicate.communicate;

import com.telit.communicate.constant.CommunicateVariable;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;


/**
 * @author zhouyu
 * @description zookeeper注册
 */
@Component
public class ZookeeperRegister {


    @Autowired
    private RegisterServerStarter registerServerStarter;

    @Value("${zookeeper.enable}")
    private boolean enable;

    @Value("${zookeeper.address}")
    private String address;

    @Value("${zookeeper.timeout}")
    private int timeout;

    private ZooKeeper zooKeeper;


    /**
     * 全局客户端连接
     *
     * @return 连接句柄
     */
    @PostConstruct
    public ZooKeeper getZooKeeper() throws IOException {
        if (!enable){
            return null;
        }
        if (zooKeeper == null) {
            zooKeeper = new ZooKeeper(address, timeout, watchedEvent -> {
                if (Watcher.Event.KeeperState.Disconnected == watchedEvent.getState()) {
                    //服务端断开连接
                    CommunicateVariable.registerSuccess.compareAndSet(true, false);
                    registerServerStarter.doRegister();
                }
            });
        }
        return zooKeeper;
    }

    /**
     * 根据服务端获取访问路径
     *
     * @param server 服务端
     * @return 访问路径
     */
    public String getSendMsgUrl(String server) throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/" + server, true, null);
        return new String(data);
    }

    /**
     * 获取所有在线服务端
     *
     * @return 在线服务端名称
     */
    public List<String> getAllServer() throws KeeperException, InterruptedException {
        return zooKeeper.getChildren("/", true);
    }

    /**
     * 判断节点是否存在
     *
     * @param server 服务端
     * @return 是否存在
     */
    public boolean exists(String server) throws InterruptedException, KeeperException {
        Stat exists = zooKeeper.exists(server, true);
        return exists != null;
    }

}
